package cn.edu.live.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.live.dao.ActivityDao;
import cn.edu.live.global.GlobalObj;
import cn.edu.live.interceptor.CheckIfLoginInterceptor;
import cn.edu.live.lecloud.factory.LeCloudFactory;
import cn.edu.live.model.LiveRoom;
import cn.edu.live.status.ActivityStatus;
import cn.edu.live.status.RespStatus;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.lecloud.constant.ActivityConst;

@Before(CheckIfLoginInterceptor.class)
public class ActivityController extends Controller {

	/**
	 * 返回视频列表界面
	 */
	public void getAllLiveAct() {
		ActivityDao adao = new ActivityDao();
		List<LiveRoom> list = adao.findAllActByStatus(ActivityStatus.LIVE);

		// TODO put in the webpage.
		System.out.println("find " + list.size() + " liverooms.");

		setAttr("list", list);
		renderJsp("/activityList.jsp");
		// renderJsp("/test.jsp");
	}

	public void getAllFinishedAct() {
		ActivityDao adao = new ActivityDao();
		List<LiveRoom> list = adao.findAllActByStatus(ActivityStatus.FINISHED);

		// TODO put in webpage.

		render("");

	}

	public void getHotActivities() {

	}

	/**
	 * 进入直播间的时候获取一个直播间的信息。（进入直播间接口）,已写完，未测试。
	 */
	public void getActivity() {
		int code = RespStatus.UNKNOWN_ERROR;
		String msg = "获取直播间信息失败！请稍后重试！";

		// 检查activityId
		String activityId = getPara("activityId");
		if (activityId == null) {
			code = RespStatus.WRONG_PARAM;
			msg = "找不到该直播间！";

			setAttr("errinfo", msg);
			renderJsp("/errInfo.jsp");
			return;
		}

		// 得到播放地址
		String playAddr = LeCloudFactory.getPlayAddr(activityId);
		if (playAddr == null) {
			code = RespStatus.WRONG_PARAM;
			msg = "找不到该直播间！";

			setAttr("errinfo", msg);
			renderJsp("/errInfo.jsp");
			return;
		}

		// 数据库中获取该直播间的数据
		ActivityDao adao = new ActivityDao();
		LiveRoom liveRoom = adao.findActByActId(activityId);
		if (liveRoom == null) {
			code = RespStatus.WRONG_PARAM;
			msg = "找不到该直播间！";

			setAttr("errinfo", msg);
			renderJsp("/errInfo.jsp");
			return;
		}

		// TODO 如果当前主播不是正在直播中，需不需要处理？
		if (liveRoom.getInt("status") != ActivityStatus.LIVE) {
			msg = "主播当前不在直播，换个其他的看看?";

			setAttr("errinfo", msg);
			renderJsp("/errInfo.jsp");
			return;
		}

		// 从内存对象中加载所需数据
		int curStudents = 0;
		try {
			curStudents = GlobalObj.liveRooms.get(activityId);
			curStudents++;
			GlobalObj.liveRooms.put(activityId, curStudents);
		} catch (Exception e) {
			e.printStackTrace();
			msg = "主播当前不在直播，换个其他的看看?";

			setAttr("errinfo", msg);
			renderJsp("/errInfo.jsp");
			return;
		}

		// 根据需要拼接json对象
		JSONObject js = new JSONObject();
		js.put("id", liveRoom.getInt("id"));
		js.put("anchorId", liveRoom.getInt("anchorId"));
		js.put("tag", liveRoom.getStr("tag"));
		js.put("curStudents", curStudents);
		js.put("status", liveRoom.getInt("status"));
		js.put("posEvaluate", liveRoom.getInt("posEvaluate"));
		js.put("negEvaluate", liveRoom.getInt("negEvaluate"));
		js.put("playAddr", playAddr);
		js.put("activityId", activityId);
		js.put("activityName", liveRoom.getStr("activityName"));
		js.put("startTime", liveRoom.getStr("startTime"));
		js.put("endTime", liveRoom.getStr("endTime"));
		js.put("coverImgUrl", liveRoom.getStr("coverImgUrl"));
		js.put("description", liveRoom.getStr("description"));

		code = RespStatus.SUCCESS;
		msg = "";

		renderJsp("/activity.jsp");
	}

	/**
	 * 创建直播间接口，已写完，未测试</br> 返回一个json对象，例：{code:1,errMsg:"unknown error."}
	 */
	public void createActivity() {
		int code = RespStatus.UNKNOWN_ERROR;
		String msg = "创建失败，请稍后重试！";

		String activityName = getPara("activityName");
		int anchorId = getParaToInt("anchorId", -1);
		String tag = getPara("tag", "");
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String coverImgUrl = getPara("coverImgUrl", "");
		String description = getPara("description", "");

		// check param.
		if (activityName == null || anchorId == -1 || startTime == null || endTime == null) {
			code = RespStatus.WRONG_PARAM;
			msg = "参数错误，请检查输入是否正确！";

			renderJson(respJson(code, msg).toJSONString());
			return;
		}

		// 构建接口参数
		Map<String, String> map = new HashMap<>();
		map.put("activityName", activityName);
		map.put("activityCategory", ActivityConst.DEFAULT_ACTIVITYCATEGORY);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		map.put("coverImgUrl", coverImgUrl);
		map.put("description", description);
		map.put("playMode", ActivityConst.DEFAULT_PLAYMODE + "");
		map.put("liveNum", ActivityConst.DEFAULT_LIVENUM + "");
		map.put("codeRateTypes", ActivityConst.DEFAULT_CODERATETYPES + "");
		map.put("needRecord", ActivityConst.DEFAULT_NEEDRECORD + "");
		map.put("needTimeShift", ActivityConst.DEFAULT_NEEDTIMESHIFT + "");
		map.put("needFullView", ActivityConst.DEFAULT_NEEDFULLVIEW + "");

		// 调用接口
		String activityId = LeCloudFactory.createActivity(map);

		// 如果失败，
		if (activityId == null) {
			renderJson(respJson(code, msg).toJSONString());
			return;
		}

		// 成功了，创建LiveRoom对象并保存起来
		LiveRoom liveRoom = new LiveRoom();
		liveRoom.set("activityId", activityId);
		liveRoom.set("activityName", activityName);
		liveRoom.set("anchorId", anchorId);
		liveRoom.set("coverImgUrl", coverImgUrl);
		liveRoom.set("curStudents", 0);
		liveRoom.set("description", description);
		liveRoom.set("endTime", endTime);
		liveRoom.set("posEvaluate", 0);
		liveRoom.set("negEvaluate", 0);
		liveRoom.set("startTime", startTime);
		liveRoom.set("status", ActivityStatus.NOT_START);
		liveRoom.set("tag", tag);
		// 保存
		boolean success = liveRoom.save();

		if (success) {
			code = RespStatus.SUCCESS;
			msg = "创建成功！";
		}

		renderJson(respJson(code, msg));
	}

	/**
	 * 进入直播间的时候获取一个直播间的信息。（进入直播间接口）,已写完，未测试。
	 */
	public void getActivity222() {
		int code = RespStatus.UNKNOWN_ERROR;
		String msg = "获取直播间信息失败！请稍后重试！";

		// 检查activityId
		String activityId = getPara("activityId");
		if (activityId == null) {
			code = RespStatus.WRONG_PARAM;
			msg = "未知直播间id！";

			renderJson(respJson(code, msg));
			return;
		}

		// 得到播放地址
		String playAddr = LeCloudFactory.getPlayAddr(activityId);
		if (playAddr == null) {
			code = RespStatus.WRONG_PARAM;
			msg = "未知直播间id！";

			renderJson(respJson(code, msg));
			return;
		}

		// 数据库中获取该直播间的数据
		ActivityDao adao = new ActivityDao();
		LiveRoom liveRoom = adao.findActByActId(activityId);
		if (liveRoom == null) {
			code = RespStatus.WRONG_PARAM;
			msg = "未知直播间id！";

			renderJson(respJson(code, msg));
			return;
		}

		// TODO 如果当前主播不是正在直播中，需不需要处理？
		if (liveRoom.getInt("status") != ActivityStatus.LIVE) {

		}

		// 从内存对象中加载所需数据
		int curStudents = GlobalObj.liveRooms.get(activityId);
		curStudents++;
		GlobalObj.liveRooms.put(activityId, curStudents);

		// 根据需要拼接json对象
		JSONObject js = new JSONObject();
		js.put("id", liveRoom.getInt("id"));
		js.put("anchorId", liveRoom.getInt("anchorId"));
		js.put("tag", liveRoom.getStr("tag"));
		js.put("curStudents", curStudents);
		js.put("status", liveRoom.getInt("status"));
		js.put("posEvaluate", liveRoom.getInt("posEvaluate"));
		js.put("negEvaluate", liveRoom.getInt("negEvaluate"));
		js.put("playAddr", playAddr);
		js.put("activityId", activityId);
		js.put("activityName", liveRoom.getStr("activityName"));
		js.put("startTime", liveRoom.getStr("startTime"));
		js.put("endTime", liveRoom.getStr("endTime"));
		js.put("coverImgUrl", liveRoom.getStr("coverImgUrl"));
		js.put("description", liveRoom.getStr("description"));

		code = RespStatus.SUCCESS;
		msg = "";

		renderJson(respJson(code, msg, js));
	}

	/**
	 * 拼接返回json对象用
	 * 
	 * @param code
	 * @param msg
	 * @return
	 */
	private JSONObject respJson(int code, String msg) {
		JSONObject js = new JSONObject();
		js.put("code", code);
		js.put("msg", msg);
		return js;
	}

	private JSONObject respJson(int code, String msg, JSONObject data) {
		JSONObject js = new JSONObject();
		js.put("code", code);
		js.put("msg", msg);
		js.put("data", data);
		return js;
	}

}
